#!/usr/bin/env python3
import os
import subprocess
import time

def get_child_pids(pid):
    """获取指定进程的所有子进程PID"""
    try:
        output = subprocess.check_output(['ps', '--ppid', str(pid), '-o', 'pid', '--no-headers'])
        return [int(pid) for pid in output.decode().strip().split('\n') if pid]
    except subprocess.CalledProcessError:
        return []

def get_pss(pid):
    """获取进程的PSS值（单位：KB）"""
    try:
        pss = 0
        smaps_path = f'/proc/{pid}/smaps'
        if os.path.exists(smaps_path):
            with open(smaps_path, 'r') as f:
                content = f.read()
                for line in content.split('\n'):
                    if line.startswith('Pss:'):
                        pss += int(line.split()[1])
        return pss
    except (IOError, ValueError):
        return 0

def get_process_tree_memory(pid):
    """递归计算进程树的总内存使用量"""
    total_pss = get_pss(pid)
    
    # 获取所有子进程
    children = get_child_pids(pid)
    
    # 递归计算所有子进程的内存使用
    for child_pid in children:
        total_pss += get_process_tree_memory(child_pid)
    
    return total_pss

def main():
    pid = int(input("请输入进程PID: "))
    while True:
        total_memory = get_process_tree_memory(pid)
        print(f"进程树总PSS内存使用: {total_memory:,} KB ({total_memory:.2f} KB)")
        time.sleep(1)

if __name__ == '__main__':
    main()